package com.lark.wifi.ui;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.cdl.library.adapter.BaseQuickAdapter;
import com.cdl.library.adapter.BaseViewHolder;
import com.cdl.library.adapter.QuickAdapter;
import com.cdl.library.adapter.listener.OnItemClickListener;
import com.cdl.library.listener.MoreButtonToggleListener;
import com.mtk.launcher.R;
import com.lark.wifi.base.IWifi;
import com.lark.wifi.base.NetWorkUtils;
import com.lark.wifi.base.OnWifiChangeListener;
import com.lark.wifi.base.OnWifiConnectListener;
import com.lark.wifi.base.OnWifiStateChangeListener;
import com.lark.wifi.base.State;
import com.lark.wifi.base.WifiManager;
import com.lark.wifi.dialog.MyWifiDialog;
import com.lark.wifi.dialog.TipWifiDialog;
import com.lark.wifi.dialog.WifiHandleDialog;
import com.lark.wifi.entity.WifiEntry;
import com.lark.wifi.util.MyLog;
import com.mtk.launcher.databinding.ActivitySettingWifiBinding;
import com.mtk.launcher.activity.BaseActivity;

import java.util.ArrayList;
import java.util.List;

public class WifiActivity extends BaseActivity {

    ActivitySettingWifiBinding binding;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivitySettingWifiBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        initWifiManager();
        initAdapter();
        initAdapterMine();
        initListener();
        updateMainView();
    }

    private void initAdapterMine() {
        binding.recyWifiMy.setLayoutManager(new LinearLayoutManager(WifiActivity.this));
        adapterWifiMine = new QuickAdapter<IWifi>(R.layout.item_wifi_info) {
            @Override
            protected void convert(BaseViewHolder viewHolder, IWifi controlEnity,int position) {
                String wifiName = controlEnity.name();
                viewHolder.setText(R.id.tv_wifi_name, wifiName);
                boolean isNeedPass = controlEnity.isEncrypt();
                if (isNeedPass) {
                    viewHolder.setVisible(R.id.iv_lock, true);
                } else {
                    viewHolder.setVisible(R.id.iv_lock, true);
                }
                int imageId = wifiManager.getWifiImageShowByLevel(controlEnity.level());
                viewHolder.setImageResource(R.id.iv_wifi_level, imageId);
                boolean isConnect = controlEnity.isConnected();
                viewHolder.setVisible(R.id.iv_content_wifi, isConnect);
                viewHolder.setVisible(R.id.view_line,true);
                if (position==0){
                    viewHolder.setVisible(R.id.view_line,false);
                }
            }
        };
        binding.recyWifiMy.setAdapter(adapterWifiMine);
        //adb shell pm path com.lark.guardiantool
        adapterWifiMine.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter<?, ?> baseAdapter, View view, int position) {
                IWifi item = (IWifi) baseAdapter.getItem(position);
                if (item.isConnected()) {
                    showWifiDetailDialog(item);
                    return;
                }
                showWifiSaveHanlderDIalog(item);
            }
        });
    }

    WifiManager wifiManager;

    private void initWifiManager() {
        wifiManager = (WifiManager) WifiManager.create(WifiActivity.this);
        boolean isEnable = wifiManager.isOpened();
        binding.toggleSwitchWifi.setSwitchStatues(isEnable);
        updateConnectStatues("程序启动");
        wifiManager.setOnWifiChangeListener(new OnWifiChangeListener() {
            @Override
            public void onWifiChanged(List<IWifi> wifiList) {
                binding.tvRefresh.setClickable(true);
                // wifi列表变化监听。包含WiFi数目变化，WiFi状态变化等，用户只需要展示即可
                showWifiDialogShow(false);
                if (wifiList == null || wifiList.size() < 1) {
                    MyLog.wifi("wifi列表变化监听==0");
                    adapterWifi.setNewData(null);
                    adapterWifiMine.setNewData(null);
                    binding.linWifiMine.setVisibility(View.GONE);
                    updateConnectStatues("WIFI列表发生变化，没有WIFI数据");
                    return;
                }
                MyLog.wifi("wifi列表变化监听==" + wifiList.size());
                List<IWifi> wifisMine = new ArrayList<>();
                List<IWifi> wifisCanUse = new ArrayList<>();
                for (IWifi wifiCache : wifiList) {
                    boolean ifHasSave = wifiCache.isSaved();
                    if (ifHasSave) {
                        wifisMine.add(wifiCache);
                    } else {
                        wifisCanUse.add(wifiCache);
                    }
                }
                MyLog.wifi("wifi列表变化监听=wifisMine=" + wifisMine.size());
                adapterWifi.setNewData(wifisCanUse);
                updateConnectStatues("WIFI数据加载完成，这里需要显示");
                if (wifisMine == null && wifisMine.size() < 1) {
                    binding.linWifiMine.setVisibility(View.GONE);
                    adapterWifiMine.setNewData(null);
                    return;
                }
                binding.linWifiMine.setVisibility(View.VISIBLE);
                adapterWifiMine.setNewData(wifisMine);
            }
        });

        wifiManager.setOnWifiConnectListener(new OnWifiConnectListener() {
            @Override
            public void onConnectChanged(boolean status) {
                MyLog.wifi("wifi连接状态变化监听==" + status);
                getWifiList("onConnectChanged");
                updateConnectStatues("wifi连接状态变化监听=连接状态变化");
            }

            @Override
            public void netStatuesChange(boolean isConnect) {
                MyLog.wifi("wifi连接状态变化监听=网络变化==" + isConnect);
                getWifiList("onConnectChanged");
                updateConnectStatues("wifi连接状态变化监听=网络变化");
            }
        });
        wifiManager.setOnWifiStateChangeListener(new OnWifiStateChangeListener() {
            @Override
            public void onStateChanged(State state) {
                MyLog.wifi("wifi连接状态回调==" + state);
                if (state == State.ENABLED) {
                    getWifiList("Wifi状态=State.ENABLED");
                }
                updateConnectStatues("wifi连接状态回调");
            }
        });
    }

    private void updateConnectStatues(String printTag) {
        boolean isConnect = NetWorkUtils.isNetworkConnected(WifiActivity.this);
        if (isConnect) {
            binding.toggleSwitchWifi.setTxtContent(getString(R.string.connected), 0xff373737);
        } else {
            binding.toggleSwitchWifi.setTxtContent(getString(R.string.not_connect), 0xffFF0000);
        }
        boolean isEnable = wifiManager.isOpened();
        if (!isEnable) {
            binding.linWifiMine.setVisibility(View.GONE);
        }
    }

    QuickAdapter adapterWifi;
    QuickAdapter adapterWifiMine;

    private void initAdapter() {
        binding.recyWifi.setLayoutManager(new LinearLayoutManager(WifiActivity.this));
        adapterWifi = new QuickAdapter<IWifi>(R.layout.item_wifi_info) {
            @Override
            protected void convert(BaseViewHolder viewHolder, IWifi controlEnity,int position) {
                String wifiName = controlEnity.name();
                viewHolder.setText(R.id.tv_wifi_name, wifiName);
                boolean isNeedPass = controlEnity.isEncrypt();
                if (isNeedPass) {
                    viewHolder.setVisible(R.id.iv_lock, true);
                } else {
                    viewHolder.setVisible(R.id.iv_lock, true);
                }
                int imageId = wifiManager.getWifiImageShowByLevel(controlEnity.level());
                viewHolder.setImageResource(R.id.iv_wifi_level, imageId);
                boolean isConnect = controlEnity.isConnected();
                viewHolder.setVisible(R.id.iv_content_wifi, isConnect);

                viewHolder.setVisible(R.id.view_line,true);
                if (position==0){
                    viewHolder.setVisible(R.id.view_line,false);
                }
            }
        };
        binding.recyWifi.setAdapter(adapterWifi);
    }

    private void initListener() {
        adapterWifi.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter<?, ?> baseAdapter, View view, int position) {
                IWifi item = (IWifi) baseAdapter.getItem(position);
                MyLog.wifi("您点击的IWFI=" + item);
                MyLog.wifi("您点击的IWFI=isConnected=" + item.isConnected());
                //已连接的wifi
                if (item.isConnected()) {
                    showWifiDetailDialog(item);
                    return;
                }
                boolean ifHasSave = item.isSaved();
                MyLog.wifi("您点击的IWFI=ifHasSave=" + ifHasSave);
                if (ifHasSave) {
                    showWifiSaveHanlderDIalog(item);
                    return;
                }
                MyLog.wifi("您点击的IWFI=需要连接=" + item);
                MyWifiDialog myWifiDialog = new MyWifiDialog(WifiActivity.this);
                myWifiDialog.setmYtitle(item)
                        .setOnLinkListener(new MyWifiDialog.WifiCallBackLink() {
                            @Override
                            public void onLink(WifiEntry wifiEntry) {
                                showWifiDialogShow(true);
                                boolean isConnect = wifiManager.connectEncryptWifi(item, wifiEntry.password);
                                MyLog.wifi("通过密码去连接WIFI=" + isConnect);
                            }
                        })
                        .show();
            }
        });

        binding.toggleSwitchWifi.setOnMoretListener(new MoreButtonToggleListener() {
            @Override
            public void switchToggleView(View view, boolean isClick) {
                boolean isOpen = wifiManager.isOpened();
                if (!isOpen) {
                    // 打开 WIFI
                    wifiManager.openWifi();
                    return;
                }
                //关闭WIFI
                showWifiDialogShow(false);
                wifiManager.closeWifi();
                adapterWifi.setNewData(null);
                adapterWifiMine.setNewData(null);
                updateConnectStatues("手动切换WIFI开关");
            }
        });

        binding.included.llBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        binding.tvRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getWifiList("点击刷新");
            }
        });
    }

    private void getWifiList(String printTag) {
        boolean isOpen = wifiManager.isOpened();
        MyLog.wifi("getWifiList==" + isOpen + " / " + printTag);
        if (!isOpen) {
            showToastView(getString(R.string.wifi_not_ues));
            return;
        }
        binding.tvRefresh.setClickable(false);
        showWifiDialogShow(true);
        wifiManager.scanWifi();
    }

    private void showWifiDialogShow(boolean isShow) {
        binding.included.progressRefresh.setVisibility(isShow ? View.VISIBLE : View.GONE);
    }

    /***
     * 点击当前已经连接的WIFI
     * @param iWifi
     */
    private void showWifiDetailDialog(IWifi iWifi) {
        TipWifiDialog tipWifiDialog = new TipWifiDialog(WifiActivity.this);
        tipWifiDialog.setParamX(100);
        tipWifiDialog.setData(iWifi);
        tipWifiDialog.setCenterListener(buttonId -> {
                    if (buttonId == R.id.tv_disconnect) {
                        //点击断开连接
                        wifiManager.disConnectWifi();
                    }
                    if (buttonId == R.id.tv_cancel_save) {
                        //点击取消保存
                        wifiManager.removeWifi(iWifi);
                    }
                })
                .show();
    }

    /***
     * 已经保存的WIFI
     */
    private void showWifiSaveHanlderDIalog(IWifi item) {
        WifiHandleDialog wifiHandleDialog = new WifiHandleDialog(WifiActivity.this);
        wifiHandleDialog.setData(item);
        wifiHandleDialog.setCenterListener(new WifiHandleDialog.OnButtonListener() {
            @Override
            public void onButton(int buttonId) {
                if (buttonId == R.id.tv_cancel_save) {
                    //取消保存
                    wifiManager.removeWifi(item);
                }
                if (buttonId == R.id.tv_link) {
                    showWifiDialogShow(true);
                    wifiManager.connectSavedWifi(item);
                }
            }
        });
        wifiHandleDialog.show();
    }


    private void updateMainView() {
        binding.included.title.setText(getString(R.string.wifi_net_title));
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (wifiManager != null) {
            wifiManager.destroy();
        }
        finish();
    }

    public String getApkVersionName() {
        try {
            PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            return packageInfo.versionName + " _ " + packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "N/A";
        }
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        MyLog.wifi("onConfigurationChanged==" + newConfig.orientation);
    }
}
